package de.fhkl.gatav.ut.camera5classthread;

import java.io.IOException;

import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

class CamSurfaceHolder extends SurfaceView implements SurfaceHolder.Callback{

	private SurfaceHolder surfaceHolder;
	private Camera		  cam;
	
	public CamSurfaceHolder(Context context, AttributeSet attrs){
		super(context,attrs);
		surfaceHolder = getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		// TODO Auto-generated method stub
	    // Now that the size is known, set up the camera parameters and begin
	    // the preview.
		Log.d("CCamSurfaceHolder","surfaceChanged");
	    Camera.Parameters parameters = cam.getParameters();
	    parameters.setPreviewSize(width, height);
	    parameters.setPictureFormat(PixelFormat.JPEG);
	    cam.setParameters(parameters);
	    cam.startPreview();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
	    // The Surface has been created, acquire the camera and tell it where
	    // to draw.
		if (cam==null){
			cam = Camera.open();
		}
	    try {
	    	cam.setPreviewDisplay(holder);
	    } catch (IOException exception) {
	    	cam.release();
	    	cam = null;
	        // TODO: add more exception handling logic here
	    }
	    Log.d("CCamSurfaceHolder","surfaceCreated");
	}

	public boolean startPrev(){
		if (cam!=null){
			cam.startPreview();
			return true;
		}else{
			return false;
		}
	}
	
	public boolean stopPrev(){
		if (cam!=null){
			cam.startPreview();
			return true;
		}else{
			return false;
		}
	}
	
	public void releaseCam(){
		if (cam!=null){
			cam.stopPreview();
			cam.release();
			cam = null;			
		}
	}
	
	public void reOpenCam(){
		if (cam==null){
			cam = Camera.open();
		}
	}
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
	    // Surface will be destroyed when we return, so stop the preview.
	    // Because the CameraDevice object is not a shared resource, it's very
	    // important to release it when the activity is paused.
		if (cam!=null){
			cam.stopPreview();
			cam.release();
			cam=null;
		}
	}

}